<template>
  <div class="config-container" v-loading="loading">
    <el-tabs v-model="activeTab" type="border-card" class="config-tabs">
      <el-tab-pane label="基本设置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          label-width="120px"
          :rules="basicRules"
          class="config-form"
        >
          <el-form-item label="系统名称" prop="systemName">
            <el-input v-model="basicForm.systemName" />
          </el-form-item>
          <el-form-item label="系统Logo">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeLogoUpload"
              :http-request="uploadLogo"
            >
              <img v-if="basicForm.logo" :src="basicForm.logo" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议尺寸：200x60px，支持jpg、png、gif格式</div>
          </el-form-item>
          <el-form-item label="系统描述" prop="description">
            <el-input v-model="basicForm.description" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="底部版权" prop="footer">
            <el-input v-model="basicForm.footer" />
          </el-form-item>
          <el-form-item label="备案号" prop="icp">
            <el-input v-model="basicForm.icp" placeholder="例如：京ICP备12345678号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveBasicConfig">保存设置</el-button>
            <el-button @click="resetBasicForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="安全设置" name="security">
        <el-form
          ref="securityFormRef"
          :model="securityForm"
          label-width="150px"
          :rules="securityRules"
          class="config-form"
        >
          <el-form-item label="账户锁定阈值" prop="loginRetryLimit">
            <el-input-number v-model="securityForm.loginRetryLimit" :min="1" :max="10" />
            <span class="form-tip">次，用户登录失败达到此次数将锁定账户</span>
          </el-form-item>
          <el-form-item label="账户锁定时间" prop="lockTime">
            <el-input-number v-model="securityForm.lockTime" :min="1" :max="1440" />
            <span class="form-tip">分钟，锁定时间内无法登录</span>
          </el-form-item>
          <el-form-item label="密码过期时间" prop="passwordExpireDays">
            <el-input-number v-model="securityForm.passwordExpireDays" :min="0" :max="365" />
            <span class="form-tip">天，0表示永不过期</span>
          </el-form-item>
          <el-form-item label="会话超时时间" prop="sessionTimeout">
            <el-input-number v-model="securityForm.sessionTimeout" :min="10" :max="1440" />
            <span class="form-tip">分钟，超时后需要重新登录</span>
          </el-form-item>
          <el-form-item label="密码强度要求" prop="passwordStrength">
            <el-select v-model="securityForm.passwordStrength">
              <el-option label="低（仅字母或数字）" value="low" />
              <el-option label="中（字母+数字）" value="medium" />
              <el-option label="高（字母+数字+特殊字符）" value="high" />
            </el-select>
          </el-form-item>
          <el-form-item label="启用两步验证" prop="enableTwoFactor">
            <el-switch v-model="securityForm.enableTwoFactor" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveSecurityConfig">保存设置</el-button>
            <el-button @click="resetSecurityForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="邮件配置" name="email">
        <el-form
          ref="emailFormRef"
          :model="emailForm"
          label-width="120px"
          :rules="emailRules"
          class="config-form"
        >
          <el-form-item label="SMTP服务器" prop="smtpServer">
            <el-input v-model="emailForm.smtpServer" placeholder="例如：smtp.example.com" />
          </el-form-item>
          <el-form-item label="SMTP端口" prop="smtpPort">
            <el-input-number v-model="emailForm.smtpPort" :min="1" :max="65535" />
          </el-form-item>
          <el-form-item label="邮箱账号" prop="email">
            <el-input v-model="emailForm.email" placeholder="例如：admin@example.com" />
          </el-form-item>
          <el-form-item label="邮箱密码" prop="password">
            <el-input v-model="emailForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="发件人姓名" prop="senderName">
            <el-input v-model="emailForm.senderName" placeholder="显示的发件人姓名" />
          </el-form-item>
          <el-form-item label="启用SSL" prop="ssl">
            <el-switch v-model="emailForm.ssl" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEmailConfig">保存设置</el-button>
            <el-button @click="resetEmailForm">重置</el-button>
            <el-button type="success" @click="testEmailConfig">发送测试邮件</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="存储配置" name="storage">
        <el-form
          ref="storageFormRef"
          :model="storageForm"
          label-width="150px"
          class="config-form"
        >
          <el-form-item label="默认存储方式" prop="defaultStorage">
            <el-radio-group v-model="storageForm.defaultStorage">
              <el-radio label="local">本地存储</el-radio>
              <el-radio label="oss">阿里云OSS</el-radio>
              <el-radio label="cos">腾讯云COS</el-radio>
              <el-radio label="qiniu">七牛云存储</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="storageForm.defaultStorage === 'local'">
            <el-form-item label="上传路径" prop="uploadPath">
              <el-input v-model="storageForm.local.uploadPath" placeholder="/path/to/upload/directory" />
            </el-form-item>
            <el-form-item label="文件大小限制" prop="maxSize">
              <el-input-number v-model="storageForm.local.maxSize" :min="1" :max="500" />
              <span class="form-tip">MB</span>
            </el-form-item>
            <el-form-item label="允许的文件类型" prop="allowedTypes">
              <el-select v-model="storageForm.local.allowedTypes" multiple placeholder="请选择">
                <el-option label="图片文件" value="image" />
                <el-option label="文档文件" value="document" />
                <el-option label="音视频文件" value="media" />
                <el-option label="压缩文件" value="archive" />
              </el-select>
            </el-form-item>
          </template>

          <template v-else-if="storageForm.defaultStorage === 'oss'">
            <el-form-item label="Endpoint" prop="endpoint">
              <el-input v-model="storageForm.oss.endpoint" placeholder="oss-cn-beijing.aliyuncs.com" />
            </el-form-item>
            <el-form-item label="AccessKey ID" prop="accessKeyId">
              <el-input v-model="storageForm.oss.accessKeyId" />
            </el-form-item>
            <el-form-item label="AccessKey Secret" prop="accessKeySecret">
              <el-input v-model="storageForm.oss.accessKeySecret" show-password />
            </el-form-item>
            <el-form-item label="Bucket" prop="bucket">
              <el-input v-model="storageForm.oss.bucket" />
            </el-form-item>
          </template>

          <el-form-item>
            <el-button type="primary" @click="saveStorageConfig">保存设置</el-button>
            <el-button @click="resetStorageForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="数据库配置" name="database">
        <el-form
          ref="dbFormRef"
          :model="dbForm"
          label-width="120px"
          :rules="dbRules"
          class="config-form"
        >
          <el-form-item label="数据库类型" prop="type">
            <el-select v-model="dbForm.type">
              <el-option label="MySQL" value="mysql" />
              <el-option label="PostgreSQL" value="postgresql" />
              <el-option label="SQL Server" value="sqlserver" />
              <el-option label="SQLite" value="sqlite" />
            </el-select>
          </el-form-item>
          <el-form-item label="主机地址" prop="host">
            <el-input v-model="dbForm.host" placeholder="localhost" />
          </el-form-item>
          <el-form-item label="端口" prop="port">
            <el-input-number v-model="dbForm.port" :min="1" :max="65535" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="dbForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="dbForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="数据库名" prop="database">
            <el-input v-model="dbForm.database" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveDbConfig">保存设置</el-button>
            <el-button @click="resetDbForm">重置</el-button>
            <el-button type="success">测试连接</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfigList, createConfig, updateConfig, deleteConfig } from '@/api/system'

// 激活的标签页
const activeTab = ref('basic')

// 加载状态
const loading = ref(false)

// 系统配置数据
const configData = ref({})

// 从API加载配置数据
const loadConfigData = async () => {
  loading.value = true
  try {
    // 获取基本配置
    const basicRes = await getConfigList({ group: 'basic' })
    const securityRes = await getConfigList({ group: 'security' })
    const emailRes = await getConfigList({ group: 'email' })
    const storageRes = await getConfigList({ group: 'storage' })
    const otherRes = await getConfigList({ group: 'other' })

    // 处理配置数据
    const formatConfigs = (configs) => {
      const result = {}
      if (configs && configs.items) {
        configs.items.forEach(item => {
          // 尝试解析JSON值
          try {
            result[item.config_key] = JSON.parse(item.config_value)
          } catch (e) {
            // 不是JSON，直接使用原值
            result[item.config_key] = item.config_value
          }
          // 保存配置ID，用于更新
          result[`${item.config_key}_id`] = item.id
        })
      }
      return result
    }

    // 设置表单数据
    const basic = formatConfigs(basicRes)
    const security = formatConfigs(securityRes)
    const email = formatConfigs(emailRes)
    const storage = formatConfigs(storageRes)
    const other = formatConfigs(otherRes)

    // 更新表单
    Object.assign(basicForm, {
      systemName: basic.systemName || '后台管理系统',
      logo: basic.logo || '',
      description: basic.description || '',
      footer: basic.footer || '',
      icp: basic.icp || '',
      systemNameId: basic.systemName_id,
      logoId: basic.logo_id,
      descriptionId: basic.description_id,
      footerId: basic.footer_id,
      icpId: basic.icp_id
    })

    Object.assign(securityForm, {
      loginRetryLimit: security.loginRetryLimit || 5,
      lockTime: security.lockTime || 30,
      passwordExpireDays: security.passwordExpireDays || 90,
      sessionTimeout: security.sessionTimeout || 120,
      passwordStrength: security.passwordStrength || 'medium',
      enableTwoFactor: security.enableTwoFactor || false,
      loginRetryLimitId: security.loginRetryLimit_id,
      lockTimeId: security.lockTime_id,
      passwordExpireDaysId: security.passwordExpireDays_id,
      sessionTimeoutId: security.sessionTimeout_id,
      passwordStrengthId: security.passwordStrength_id,
      enableTwoFactorId: security.enableTwoFactor_id
    })

    Object.assign(emailForm, {
      smtpServer: email.smtpServer || '',
      smtpPort: email.smtpPort || 465,
      email: email.email || '',
      password: email.password || '',
      senderName: email.senderName || '',
      ssl: email.ssl || true,
      smtpServerId: email.smtpServer_id,
      smtpPortId: email.smtpPort_id,
      emailId: email.email_id,
      passwordId: email.password_id,
      senderNameId: email.senderName_id,
      sslId: email.ssl_id
    })

    Object.assign(storageForm, {
      defaultStorage: storage.defaultStorage || 'local',
      local: storage.local || {
        uploadPath: '/uploads',
        maxSize: 50,
        allowedTypes: ['image', 'document']
      },
      oss: storage.oss || {
        endpoint: '',
        accessKeyId: '',
        accessKeySecret: '',
        bucket: ''
      },
      cos: storage.cos || {
        region: '',
        secretId: '',
        secretKey: '',
        bucket: ''
      },
      qiniu: storage.qiniu || {
        region: '',
        accessKey: '',
        secretKey: '',
        bucket: ''
      },
      defaultStorageId: storage.defaultStorage_id,
      localId: storage.local_id,
      ossId: storage.oss_id,
      cosId: storage.cos_id,
      qiniuId: storage.qiniu_id
    })

    // 保存所有配置数据用于引用
    configData.value = {
      basic, security, email, storage, other
    }

  } catch (error) {
    console.error('加载配置失败:', error)
    ElMessage.error('加载配置失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 保存配置的通用方法
const saveConfig = async (group, key, value, configId) => {
  try {
    // 值为对象时转为JSON字符串
    const configValue = typeof value === 'object'
      ? JSON.stringify(value)
      : String(value)

    if (configId) {
      // 更新已有配置
      await updateConfig(configId, {
        config_value: configValue
      })
    } else {
      // 创建新配置
      await createConfig({
        config_key: key,
        config_value: configValue,
        config_description: `${group}配置项: ${key}`,
        config_group: group
      })
    }
    return true
  } catch (error) {
    console.error(`保存配置 ${key} 失败:`, error)
    throw error
  }
}

// 基本设置表单
const basicFormRef = ref(null)
const basicForm = reactive({
  systemName: '后台管理系统',
  logo: '',
  description: '',
  footer: '',
  icp: '',
  // 保存配置项ID，用于更新
  systemNameId: '',
  logoId: '',
  descriptionId: '',
  footerId: '',
  icpId: ''
})

const basicRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 保存基本设置
const saveBasicConfig = async () => {
  try {
    await basicFormRef.value.validate()

    loading.value = true

    // 保存各个配置项
    await Promise.all([
      saveConfig('basic', 'systemName', basicForm.systemName, basicForm.systemNameId),
      saveConfig('basic', 'logo', basicForm.logo, basicForm.logoId),
      saveConfig('basic', 'description', basicForm.description, basicForm.descriptionId),
      saveConfig('basic', 'footer', basicForm.footer, basicForm.footerId),
      saveConfig('basic', 'icp', basicForm.icp, basicForm.icpId)
    ])

    ElMessage.success('基本设置保存成功')

    // 重新加载配置
    await loadConfigData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置基本表单
const resetBasicForm = () => {
  const basic = configData.value.basic || {}
  basicForm.systemName = basic.systemName || '后台管理系统'
  basicForm.logo = basic.logo || ''
  basicForm.description = basic.description || ''
  basicForm.footer = basic.footer || ''
  basicForm.icp = basic.icp || ''
}

// 安全设置表单
const securityFormRef = ref(null)
const securityForm = reactive({
  loginRetryLimit: 5,
  lockTime: 30,
  passwordExpireDays: 90,
  sessionTimeout: 120,
  passwordStrength: 'medium',
  enableTwoFactor: false,
  // 配置项ID
  loginRetryLimitId: '',
  lockTimeId: '',
  passwordExpireDaysId: '',
  sessionTimeoutId: '',
  passwordStrengthId: '',
  enableTwoFactorId: ''
})

const securityRules = {
  loginRetryLimit: [
    { required: true, message: '请输入账户锁定阈值', trigger: 'blur' }
  ],
  lockTime: [
    { required: true, message: '请输入账户锁定时间', trigger: 'blur' }
  ],
  passwordExpireDays: [
    { required: true, message: '请输入密码过期时间', trigger: 'blur' }
  ],
  sessionTimeout: [
    { required: true, message: '请输入会话超时时间', trigger: 'blur' }
  ]
}

// 保存安全设置
const saveSecurityConfig = async () => {
  try {
    await securityFormRef.value.validate()

    loading.value = true

    // 保存各个配置项
    await Promise.all([
      saveConfig('security', 'loginRetryLimit', securityForm.loginRetryLimit, securityForm.loginRetryLimitId),
      saveConfig('security', 'lockTime', securityForm.lockTime, securityForm.lockTimeId),
      saveConfig('security', 'passwordExpireDays', securityForm.passwordExpireDays, securityForm.passwordExpireDaysId),
      saveConfig('security', 'sessionTimeout', securityForm.sessionTimeout, securityForm.sessionTimeoutId),
      saveConfig('security', 'passwordStrength', securityForm.passwordStrength, securityForm.passwordStrengthId),
      saveConfig('security', 'enableTwoFactor', securityForm.enableTwoFactor, securityForm.enableTwoFactorId)
    ])

    ElMessage.success('安全设置保存成功')

    // 重新加载配置
    await loadConfigData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置安全表单
const resetSecurityForm = () => {
  const security = configData.value.security || {}
  securityForm.loginRetryLimit = security.loginRetryLimit || 5
  securityForm.lockTime = security.lockTime || 30
  securityForm.passwordExpireDays = security.passwordExpireDays || 90
  securityForm.sessionTimeout = security.sessionTimeout || 120
  securityForm.passwordStrength = security.passwordStrength || 'medium'
  securityForm.enableTwoFactor = security.enableTwoFactor || false
}

// 邮件配置表单
const emailFormRef = ref(null)
const emailForm = reactive({
  smtpServer: '',
  smtpPort: 465,
  email: '',
  password: '',
  senderName: '',
  ssl: true,
  // 配置项ID
  smtpServerId: '',
  smtpPortId: '',
  emailId: '',
  passwordId: '',
  senderNameId: '',
  sslId: ''
})

const emailRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' }
  ],
  senderName: [
    { required: true, message: '请输入发件人姓名', trigger: 'blur' }
  ]
}

// 保存邮件设置
const saveEmailConfig = async () => {
  try {
    await emailFormRef.value.validate()

    loading.value = true

    // 保存各个配置项
    await Promise.all([
      saveConfig('email', 'smtpServer', emailForm.smtpServer, emailForm.smtpServerId),
      saveConfig('email', 'smtpPort', emailForm.smtpPort, emailForm.smtpPortId),
      saveConfig('email', 'email', emailForm.email, emailForm.emailId),
      saveConfig('email', 'password', emailForm.password, emailForm.passwordId),
      saveConfig('email', 'senderName', emailForm.senderName, emailForm.senderNameId),
      saveConfig('email', 'ssl', emailForm.ssl, emailForm.sslId)
    ])

    ElMessage.success('邮件设置保存成功')

    // 重新加载配置
    await loadConfigData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置邮件表单
const resetEmailForm = () => {
  const email = configData.value.email || {}
  emailForm.smtpServer = email.smtpServer || ''
  emailForm.smtpPort = email.smtpPort || 465
  emailForm.email = email.email || ''
  emailForm.password = email.password || ''
  emailForm.senderName = email.senderName || ''
  emailForm.ssl = email.ssl || true
}

// 测试邮件配置
const testEmailConfig = () => {
  ElMessage.success('测试邮件已发送')
}

// 存储配置表单
const storageFormRef = ref(null)
const storageForm = reactive({
  defaultStorage: 'local',
  local: {
    uploadPath: '/uploads',
    maxSize: 50,
    allowedTypes: ['image', 'document']
  },
  oss: {
    endpoint: '',
    accessKeyId: '',
    accessKeySecret: '',
    bucket: ''
  },
  cos: {
    region: '',
    secretId: '',
    secretKey: '',
    bucket: ''
  },
  qiniu: {
    region: '',
    accessKey: '',
    secretKey: '',
    bucket: ''
  },
  // 配置项ID
  defaultStorageId: '',
  localId: '',
  ossId: '',
  cosId: '',
  qiniuId: ''
})

// 保存存储设置
const saveStorageConfig = async () => {
  try {
    if (storageFormRef.value) {
      await storageFormRef.value.validate()
    }

    loading.value = true

    // 保存各个配置项
    await Promise.all([
      saveConfig('storage', 'defaultStorage', storageForm.defaultStorage, storageForm.defaultStorageId),
      saveConfig('storage', 'local', storageForm.local, storageForm.localId),
      saveConfig('storage', 'oss', storageForm.oss, storageForm.ossId),
      saveConfig('storage', 'cos', storageForm.cos, storageForm.cosId),
      saveConfig('storage', 'qiniu', storageForm.qiniu, storageForm.qiniuId)
    ])

    ElMessage.success('存储设置保存成功')

    // 重新加载配置
    await loadConfigData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置存储表单
const resetStorageForm = () => {
  const storage = configData.value.storage || {}
  storageForm.defaultStorage = storage.defaultStorage || 'local'
  storageForm.local = storage.local || {
    uploadPath: '/uploads',
    maxSize: 50,
    allowedTypes: ['image', 'document']
  }
  storageForm.oss = storage.oss || {
    endpoint: '',
    accessKeyId: '',
    accessKeySecret: '',
    bucket: ''
  }
  storageForm.cos = storage.cos || {
    region: '',
    secretId: '',
    secretKey: '',
    bucket: ''
  }
  storageForm.qiniu = storage.qiniu || {
    region: '',
    accessKey: '',
    secretKey: '',
    bucket: ''
  }
}

// 上传Logo前的处理
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('Logo只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过2MB!')
  }
  return isImage && isLt2M
}

// 上传Logo
const uploadLogo = (options) => {
  const { file } = options
  // 实际项目中应该调用文件上传接口
  // 这里简单的使用FileReader模拟
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    basicForm.logo = reader.result
  }
}

// 数据库配置表单
const dbFormRef = ref(null)
const dbForm = reactive({
  type: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: '',
  database: 'datatkadmin',
  // 配置项ID
  typeId: '',
  hostId: '',
  portId: '',
  usernameId: '',
  passwordId: '',
  databaseId: ''
})

const dbRules = {
  host: [
    { required: true, message: '请输入数据库主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入数据库端口', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入数据库用户名', trigger: 'blur' }
  ],
  database: [
    { required: true, message: '请输入数据库名', trigger: 'blur' }
  ]
}

// 保存数据库设置
const saveDbConfig = async () => {
  try {
    await dbFormRef.value.validate()

    loading.value = true

    // 保存各个配置项
    await Promise.all([
      saveConfig('database', 'type', dbForm.type, dbForm.typeId),
      saveConfig('database', 'host', dbForm.host, dbForm.hostId),
      saveConfig('database', 'port', dbForm.port, dbForm.portId),
      saveConfig('database', 'username', dbForm.username, dbForm.usernameId),
      saveConfig('database', 'password', dbForm.password, dbForm.passwordId),
      saveConfig('database', 'database', dbForm.database, dbForm.databaseId)
    ])

    ElMessage.success('数据库设置保存成功')

    // 重新加载配置
    await loadConfigData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置数据库表单
const resetDbForm = () => {
  const database = configData.value.database || {}
  dbForm.type = database.type || 'mysql'
  dbForm.host = database.host || 'localhost'
  dbForm.port = database.port || 3306
  dbForm.username = database.username || 'root'
  dbForm.password = database.password || ''
  dbForm.database = database.database || 'datatkadmin'
}

// 加载配置
onMounted(() => {
  loadConfigData()
})
</script>

<style scoped>
.config-container {
  padding: 20px;
  height: calc(100vh - 180px);
  overflow: auto;
}

.config-tabs {
  margin-bottom: 20px;
}

.config-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
}

.avatar-uploader {
  width: 200px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 10px;
}

.form-tip {
  margin-left: 10px;
  color: #606266;
  font-size: 13px;
}
</style>
